package zhoufu.sz.sanxiao_check.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Vector;

import zhoufu.sz.sanxiao_check.R;
import zhoufu.sz.sanxiao_check.models.StreetListModel;
import zhoufu.sz.sanxiao_check.models.User;
import zhoufu.sz.sanxiao_check.ui.basic.BasicMsgItem1Activity;
import zhoufu.sz.sanxiao_check.utils.UIUtils;
import zhoufu.sz.sanxiao_check.weiget.zxing.camera.CameraManager;
import zhoufu.sz.sanxiao_check.weiget.zxing.decoding.CaptureActivityHandler;
import zhoufu.sz.sanxiao_check.weiget.zxing.decoding.InactivityTimer;
import zhoufu.sz.sanxiao_check.weiget.zxing.view.ViewfinderView;


public class CaptureActivity extends BaseActivity implements Callback {

    private static final String TAG = CaptureActivity.class.getSimpleName();
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private TextView txtResult;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private String placeNo;

    String zxing_code_id;//扫一扫 1为 首页  2为房屋编码

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化 CameraManager
        CameraManager.init(this);
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        txtResult = (TextView) findViewById(R.id.txtResult);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        zxing_code_id = getIntent().getStringExtra("zxing_code_id");
    }

    @Override
    protected void initInject() {

    }

    @Override
    protected int setIndividualId() {
        return R.layout.activity_capture;
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    /**
     * 扫描成功返回结果
     * 186 2031 1168
     *
     * @param result  结果
     * @param barcode Bitmap
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        viewfinderView.drawResultBitmap(barcode);
        playBeepSoundAndVibrate();
        String text = result.getText();
        Log.e(TAG, "text------------------>" + result.getText());
        String result_str = result.getBarcodeFormat().toString() + ":" + text;
        txtResult.setText(result_str);
        if ("1".equals(zxing_code_id)) {

            String encoding_house_trim = text.trim();
            if (encoding_house_trim.length() < 25) {
                UIUtils.showSnackbar(viewfinderView, "无效的房屋编码");
                finish();
                return;
            }
            String encoding_house_substring = encoding_house_trim
                    .substring(encoding_house_trim.length() - 25, encoding_house_trim.length());
            Log.e(TAG, "encoding_house_substring------------------>" + encoding_house_substring);

            //mApp.ClearAllActivity();
            //mApp.isfirst = false;
            //Intent intent = new Intent();
            //            intent.putExtra("placeID", text);
            //            intent.putExtra("placeID", "");
            //            intent.putExtra("BuildingNo", encoding_house_substring);//适用于首页扫一扫出房屋编码，其他地方传空
            //            intent.putExtra("Id", "");//假数据:扫一扫的没有空铺Id不为空
            //            intent.putExtra("IsLive", "0");//假数据:与GetStreetByPager接口返回字段不一样
            //            intent.putExtra("People_Num", "0");//假数据:与GetStreetByPager接口返回字段不一样
            //            intent.putExtra("RID", "9527KP");//假数据:扫一扫的没有空铺Id不为空
            //            intent.putExtra("Address", User.readUser().getCName());
            //            intent.putExtra("StorePhoto", "");
            StreetListModel model = new StreetListModel();
            model.setPlace_No("0");
            model.setSID("0");
            model.setBuilding_No(encoding_house_substring);
            model.setRID("0");
            model.setAddress(User.readUser().getCName());
            _navigator.startStreetDetailsAct(this, model);
            finish();
        } else if ("2".equals(zxing_code_id)) {
            Intent mIntent = new Intent(this, BasicMsgItem1Activity.class);
            mIntent.putExtra("encoding_house", text);
            setResult(RESULT_OK, mIntent);
            finish();
        } else if ("3".equals(zxing_code_id)) {
            Intent mIntent = new Intent();
            try {
                text = new String(text.getBytes("ISO-8859-1"), Charset.forName("gb2312"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            mIntent.putExtra("encoding_house", getCodeAddress(text));
            setResult(RESULT_OK, mIntent);
            finish();
        }
    }

    /*
    1、至少匹配一个汉字的写法。
        2、这两个unicode值正好是Unicode表中的汉字的头和尾。
        3、"[]"代表里边的值出现一个就可以，后边的“+”代表至少出现1次，合起来即至少匹配一个汉字。
        */
    public static String getCodeAddress(String paramValue) {
        int firstIndex = 0;
        for (int index = 0;index<paramValue.length()-1;index++) {
// 将每一个角标的字符(字母 汉字 空格等)一次转换成字符串
            String w=paramValue.substring(index, index+1);
//  而java采用unicode编码，汉字的范围是 "\u4e00"（一）到"\u9fa5"（龥）
            if(w.compareTo("\u4e00")>0&&w.compareTo("\u9fa5")<0) {
                firstIndex = index;// 获取第一个汉字索引位置 跳出循环
                break;
            }
        }
        return paramValue.substring(firstIndex,paramValue.lastIndexOf("号")+1);
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };
}